package org.apache.webapp.balancer.rules;

import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import common.logging.WebPortalLogger;


/**
 * This rule generates a random number and based on the number
 * redirects to a different URL.
 *
 * @author Srini Penchikala
 */
public class RandomRedirectRule extends BaseLoadBalancingRule {

	private static Random random = new Random(System.currentTimeMillis());

	/**
	 * @see org.apache.webapp.balancer.Rule#matches(HttpServletRequest)
	 *
	 * Generate a random number and then redirect.
	 */
	public boolean matches(HttpServletRequest request) {

		WebPortalLogger.info("getServerInstance() : " + getServerInstance());
		WebPortalLogger.info("getMaxServerInstances() : " + getMaxServerInstances());
		int instance = Integer.parseInt(getServerInstance());
		int maxInstances = Integer.parseInt(getMaxServerInstances());
      String host = getTcpListenAddress();
      int port = Integer.parseInt(getTcpListenPort());
      String webPage = getTestWebPage();

		int randomNumber = random.nextInt();
		if (randomNumber > maxInstances) {
			int abs = randomNumber%maxInstances;
			WebPortalLogger.info(randomNumber + " : " + (abs+1));
         int randomInstance = abs+1;
         if (randomInstance == instance) {
            WebPortalLogger.info("Requested server instance match..");
            // Check if the node is available or not
            boolean isAlive = isServerAlive(host, port);
//            boolean isAlive = isServerAlive(webPage);
            WebPortalLogger.info("RandomRedirectRule -- isAlive : " + isAlive);
            return isAlive;
//            return true;
         } else {
            WebPortalLogger.info("Requested server instance did not match..");
            return false;
         }
		}
      return false;
	}

    /**
     * Returns a String representation of this object.
     *
     * @return String
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[");
        buffer.append(getClass().getName());
        buffer.append(": ");

        buffer.append("Redirect URL: ");
        buffer.append(getRedirectUrl());

        buffer.append("]");

        return buffer.toString();
    }
}
// End of RandomRedirectRule.java
